package cn.com.cym.gamezao.service.recruit.impl;

import cn.com.cym.gamezao.base.ResultResponse;
import cn.com.cym.gamezao.entity.authorize.User;
import cn.com.cym.gamezao.entity.xmu.recruit.LearnExperience;
import cn.com.cym.gamezao.exception.BaseException;
import cn.com.cym.gamezao.jwt.RequestUser;
import cn.com.cym.gamezao.repository.xmu.recruit.LearnExperienceRepository;
import cn.com.cym.gamezao.service.recruit.LearnExperienceService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional(rollbackFor = Exception.class)
public class LearnExperienceImpl implements LearnExperienceService {

    final LearnExperienceRepository learnExperienceRepository;

    LearnExperienceImpl(LearnExperienceRepository learnExperienceRepository){
        this.learnExperienceRepository = learnExperienceRepository;
    }

    @Override
    public List<LearnExperience> searchByCurrentUser() {
        final User user = RequestUser.get();
        if(user.getUserType() == null){
            throw new BaseException("没有获取权限",new ResultResponse("没有获取权限",403));
        }
        return this.learnExperienceRepository.findAllByUser(user);
    }

    @Override
    public List<LearnExperience> searchByCurrentUserId(Long userId) {
        return this.learnExperienceRepository.findAllByUserId(userId);
    }

    @Override
    public int save(LearnExperience learnExperience) {
        final User user = RequestUser.get();
        learnExperience.setUser(user);
        this.learnExperienceRepository.save(learnExperience);
        // 执行缓存刷新，避免线程数据获取失败
        this.learnExperienceRepository.flush();
        return 1;
    }

    @Override
    public int update(LearnExperience learnExperience, Long id) {
        final User user = RequestUser.get();
        LearnExperience byId = this.learnExperienceRepository.findById(id).get();
        if(!byId.getUser().getUserName().equals(user.getUserName())){
            throw new BaseException("没有修改他人信息权限",new ResultResponse("没有修改他人信息权限",401));
        }
        // 复制
        learnExperience.setUser(user).setId(id);
        BeanUtils.copyProperties(learnExperience,byId);
        this.learnExperienceRepository.save(byId);
        return 1;
    }

    @Override
    public void deleteById(Long id) {
        this.learnExperienceRepository.deleteById(id);
    }

    @Override
    public List<LearnExperience> findAllByUser(User user) {
        return this.learnExperienceRepository.findAllByUser(user);
    }
}
